package cn.jwcat.utils;

import cn.jwcat.entity.Ipaddress;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;

@Slf4j
@Component
public class IPUtils {

	private static Searcher searcher;

	/**
	 * 在服务启动时加载 ip2region.db 到内存中
	 * 解决打包jar后找不到 ip2region.db 的问题
	 */
	@PostConstruct
	private static void initIp2regionResource() {
		try {
			InputStream inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
			byte[] dbBinStr = FileCopyUtils.copyToByteArray(inputStream);
			// 创建一个完全基于内存的查询对象
			searcher = Searcher.newWithBuffer(dbBinStr);
		} catch (Exception e) {
			log.info("failed to create content cached searcher: %s\n", e);
		}
	}

	/**
	 * 获取客户端IP地址
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = null;
		ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
				//根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					log.error("getIpAddress exception:", e);
				}
				assert inet != null;
				ip = inet.getHostAddress();
			}
		}
		return ip;
	}

	/**
	 * 分割IP的具体位置
	 */
	public Ipaddress delRegionToIpAddress(String ip) {
		String region = null;
		try {
			region = searcher.search(ip);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		// 国家|区域|省份|城市|ISP
		String[] splitIp = region.split("\\|");
		LocalDateTime localDateTime = LocalDateTime.now();
		return new Ipaddress(null, splitIp[0], splitIp[1], splitIp[2], splitIp[3], splitIp[4], localDateTime, ip);
	}
}


// SELECT * FROM s_area a, s_staff_area sa,s_staff s,s_room r WHERE s.staff_id=sa.staff_id and sa.area_id=r.area_id and s.staff_id=35  and sa.area_id=a.area_id

